package com.shuda.common.controller;

import com.shuda.common.dto.ChangePasswordDTO;
import com.shuda.common.dto.LoginDTO;
import com.shuda.common.dto.UserProfileDTO;
import com.shuda.common.result.Result;
import com.shuda.common.security.JwtTokenProvider;
import com.shuda.business.user.service.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户管理控制器类
 */
@RestController
@RequestMapping("/api/user")
@Tag(name = "用户管理", description = "用户管理相关接口")
@RequiredArgsConstructor
@Validated
public class UserController {

    private final AuthService authService;
    private final JwtTokenProvider tokenProvider;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginDTO loginDTO) {
        Map<String, Object> result = authService.login(loginDTO);
        return Result.success(result);
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    @Operation(summary = "用户登出")
    public Result<String> logout() {
        authService.logout();
        return Result.success("登出成功");
    }

    /**
     * 刷新令牌
     */
    @PostMapping("/refresh")
    @Operation(summary = "刷新令牌")
    public Result<Map<String, Object>> refresh(@RequestParam String refreshToken) {
        String username = tokenProvider.getUsernameFromToken(refreshToken);
        if (username != null && tokenProvider.validateToken(refreshToken)) {
            String newAccessToken = tokenProvider.generateAccessToken(username);
            String newRefreshToken = tokenProvider.generateRefreshToken(username);
            Map<String, Object> result = new HashMap<>();
            result.put("accessToken", newAccessToken);
            result.put("refreshToken", newRefreshToken);
            return Result.success(result);
        }
        return Result.error("刷新令牌无效");
    }

    /**
     * 获取用户个人信息
     */
    @GetMapping("/profile")
    @Operation(summary = "获取用户个人信息")
    public Result<UserProfileDTO> getProfile() {
        UserProfileDTO profile = authService.getProfile();
        return Result.success(profile);
    }

    /**
     * 更新用户个人信息
     */
    @PutMapping("/profile")
    @Operation(summary = "更新用户个人信息")
    public Result<String> updateProfile(@Valid @RequestBody UserProfileDTO profileDTO) {
        authService.updateProfile(profileDTO);
        return Result.success("个人信息更新成功");
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    @Operation(summary = "修改密码")
    public Result<String> changePassword(@Valid @RequestBody ChangePasswordDTO changePasswordDTO) {
        authService.changePassword(changePasswordDTO);
        return Result.success("密码修改成功");
    }
}